package com.zzy.service.impl;

import com.zzy.mapper.CategoryMapper;
import com.zzy.domain.Category;
import com.zzy.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CategoryServiceImpl implements CategoryService {
    private final CategoryMapper categoryMapper;

    @Override
    public List<Category> findAll() {
        //1、查询所有数据
        List<Category> categories = categoryMapper.all();
        if(CollectionUtils.isEmpty(categories)){
            return Collections.emptyList();
        }

        //2、筛选顶级父类和所有子分类
        List<Category> parents = categories.stream().filter(c -> c.getParentId() == 0).collect(Collectors.toList());
        List<Category> children = categories.stream().filter(c -> c.getParentId() > 0).collect(Collectors.toList());

        //3、执行递归筛选
        parents.forEach(p->{
            findChildren(p,children);
        });
        return parents;
    }

    /***
     * 递归查找
     * current:当前执行查找的对象
     * all:所有子类分类数据
     */
    public void findChildren(Category current,List<Category> all){
        //循环子分类，超找当前分类的子分类
        List<Category> children = all.stream().filter(a -> Objects.equals(a.getParentId(), current.getId())).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(children)){
            //所有子分类执行递归查找
            children.forEach(c->{
                //递归查找
                findChildren(c,all);
            });
        }
        //设置子分类
        current.setChildren(children);
    }
    
    @Override
    @Transactional
    public void deleteBatch(List<Integer> ids) {
        categoryMapper.deleteBatch(ids);
    }
    
    /**
     * 新增分类
     */
    @Override
    @Transactional
    public int add(Category category) {
        return categoryMapper.add(category);
    }
    
    /**
     * 根据ID查询分类
     */
    @Override
    public Category getById(Integer id) {
        return categoryMapper.getById(id);
    }
    
    /**
     * 更新分类信息
     */
    @Override
    @Transactional
    public int update(Category category) {
        return categoryMapper.update(category);
    }
    
    /**
     * 根据ID删除分类
     */
    @Override
    @Transactional
    public int delete(Integer id) {
        return categoryMapper.delete(id);
    }
}